package com.easyfun.healthmagicbox.bluetooth.enbp;

import java.util.Arrays;

import android.util.Log;

import com.easyfun.healthmagicbox.bluetooth.MessageParser;
/**
 * Not thread safety
 * 
 * message header: 0xFD, 0xFD, end: 0x0D, 0x0A
 * 
 * 1. BP sends 0xA5
 * 2. Phone sends 0xFD, 0xFD, 0xFA, 0x0D, 0x0D, 0x0A
 * 3. BP sends 0xFD, 0xFD, 0x06, 0x0D, 0x0A
 * ... 
 * 4. BP begins to send for LED board:	[0xFD,0xFD,0xFB,PressureH, PressureL,0X0D, 0x0A]
 * PressureH*256+PressureL
 * 5。[0xFD,0xFD,0xFC, SYS,DIA,PUL, 0X0D, 0x0A] for result
 * OR
 * [0xFD,0xFD,0xFD,0x0E, 0X0D, 0x0A] error
 * SYS为收缩压,DIA为舒张压,PUL为心率. 这个数据血压会连续传5次.
 * 
 * 6. phone sends [0xFD,0xFD,0xFE, 0x06, 0X 0D, 0x0A] to shutoff BP
 * 7. BT replies: [0xFD,0xFD,0x07, 0x0D, 0x0A]
 */
public class EnBloodPressureParser extends MessageParser<EnBloodPressureMessage>{
	
	
	private static final String TAG = EnBloodPressureParser.class.getSimpleName();
	byte[] msgHeader = new byte[]{(byte) 0xFD,(byte) 0xFD};
	byte[] msgTail = new byte[]{(byte) 0x0D,(byte) 0x0A};
	
	
	/**
	 *  @param <T>
	 * @param buffer
	 * @param oneMessage
	 * @return
	 * 
	 */
	@Override
	public EnBloodPressureMessage parse(byte[] buffer1,int len) {

				
		EnBloodPressureMessage result = new EnBloodPressureMessage();
		
		int i = 0;
		while ((buffer1[i] == (byte)0xA5) && (i < len))
		{
			i++;
		}
		
		if (i>0)
		{
			if (i < len )
			{
				int leftlen = len - i;
				//copy into inner buffer
				System.arraycopy(buffer1, i, innerBuffer, innerLen, leftlen);
				
				innerLen += leftlen;
			}
			result.setRawBytes(new byte[]{(byte)0xA5});
			return result;
		}
		
		//copy into inner buffer
		System.arraycopy(buffer1, 0, innerBuffer, innerLen, len);
		innerLen += len;
		Log.i(TAG, "innerLen: " + innerLen + " innerBuffer:" + printHexString(innerBuffer));
		byte[] oneMsg = getIntegratedMessage();
		if ((oneMsg == null)||(oneMsg.length < 1))
			return null;
		result.setRawBytes(oneMsg);		
		
		result.fillin();
		return result;
	}
	
	@Override
	protected byte[] getIntegratedMessage()
	{
		
		int begin = -1;
		int end = -1;
		for (int i = 0; i < innerBuffer.length - 1; i++) {
			byte first = innerBuffer[i];
			byte second = innerBuffer[i + 1];
			if ((first==msgHeader[0])&&(second == msgHeader[1]))
			{
				//0xFD 0xFD 0xFD message
				if (begin == -1)
					begin = i;
			}else if ((first==msgTail[0])&&(second == msgTail[1]))
			{
				if (begin != -1)
					end = i + 1 + 1;
			}
			if ((begin != -1)&&(end != -1))
			{
				//one whole message.
				break;
			}
		}
	
		int msgLen = end - begin;	
		if (msgLen < 1)
			return null;
		
		byte[] integrateMsg = rearrangeBuffer(begin,end);
		 
		return integrateMsg;
	}
	
}
